<template>
  <div class="register-container">
    <div class="register-card">
      <h1 class="title">欢迎注册</h1>
      
      <!-- 头像上传区域 -->
      <div class="avatar-upload">
        <div class="avatar-preview" :style="{ backgroundImage: avatarUrl ? `url(${avatarUrl})` : 'none' }" @click="handleAvatarChange">
          <div class="upload-icon" v-if="!avatarUrl">
            <text class="icon">+</text>
          </div>
        </div>
      </div>
      
      <form>
        <div class="form-group">
          <label class="input-hint">11位手机号码</label>
          <input
            type="tel"
            v-model="phoneNumber"
            placeholder="请输入手机号码"
            class="input-field"
          >
          <p v-if="errors.phoneNumber" class="error-message">{{ errors.phoneNumber }}</p>
        </div>
        
        <div class="form-group">
          <label class="input-hint">用户名（2-16位，支持中英文）</label>
          <input
            type="text"
            v-model="userName"
            placeholder="请输入用户名"
            class="input-field"
          >
          <p v-if="errors.userName" class="error-message">{{ errors.userName }}</p>
        </div>
        
        <div class="form-group">
          <label class="input-hint">电子邮箱（例如：xxx@example.com）</label>
          <input
            type="email"
            v-model="email"
            placeholder="请输入邮箱"
            class="input-field"
          >
          <p v-if="errors.email" class="error-message">{{ errors.email }}</p>
        </div>
        
        <div class="form-group password-group">
          <label class="input-hint">密码（6-20位，包含字母和数字）</label>
          <input
            type="password"
            v-model="password"
            placeholder="请输入密码"
            class="input-field"
          >
          <p v-if="errors.password" class="error-message">{{ errors.password }}</p>
        </div>
        
        <div class="form-group password-group">
          <label class="input-hint">确认密码</label>
          <input
            type="password"
            v-model="confirmPassword"
            placeholder="请再次输入密码"
            class="input-field"
          >
          <p v-if="errors.confirmPassword" class="error-message">{{ errors.confirmPassword }}</p>
        </div>
      </form>
      
      <div class="bottom-buttons">
        <button type="button" class="register-btn" @click="submitRegistration">注册</button>
        <button type="button" class="login-btn" @click="navigateToLogin">使用已有账户登录</button>
      </div>
    </div>
  </div>
</template>

<script>
import { API_BASE_URL } from '@/utils/api-base.js'
export default {
  data() {
    return  {
      phoneNumber: '',
      userName: '',
      email: '',
      password: '',
      confirmPassword: '',
      avatarUrl: '',
      avatarFileUrl: '',
      errors: {
        phoneNumber: '',
        userName: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
    }
  },
  methods: {
    navigateToLogin() {
      // 使用redirectTo关闭当前注册页面，避免返回时回到注册页
      uni.redirectTo({
        url: '/pages/login/login'
      });
    },

    handleAvatarChange() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.avatarUrl = tempFilePath;
          this.uploadToServer(tempFilePath);
        },
        fail: (err) => {
          console.error('选择图片失败', err);
          uni.showToast({
            title: '选择图片失败',
            icon: 'none'
          });
        }
      });
    },

    uploadToServer(tempFilePath) {
      uni.showLoading({
        title: '上传中...'
      });

      uni.uploadFile({
        url: API_BASE_URL + '/api/upload/avatar', 
        filePath: tempFilePath,
        name: 'file',
        formData: {
          'type': 'avatar'
        },
        success: (uploadFileRes) => {
          uni.hideLoading();
          
          if (uploadFileRes.statusCode < 200 || uploadFileRes.statusCode >= 300) {
            console.error('上传失败，状态码:', uploadFileRes.statusCode);
            uni.showToast({
              title: `上传失败 (${uploadFileRes.statusCode})`,
              icon: 'none'
            });
            return;
          }
          
          try {
            const result = JSON.parse(uploadFileRes.data);
            if (result.success && result.url) {
              this.avatarFileUrl = result.url;
              uni.showToast({
                title: '头像上传成功',
                icon: 'success'
              });
            } else {
              throw new Error(result.message || '上传失败');
            }
          } catch (e) {
            console.error('解析上传结果失败', e, '响应数据:', uploadFileRes.data);
            uni.showToast({
              title: '上传失败: ' + (e.message || '未知错误'),
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('上传请求失败', err);
          uni.showToast({
            title: '网络错误，上传失败',
            icon: 'none'
          });
        }
      });
    },

    validateForm() {
      let isValid = true;
      this.errors = {
        phoneNumber: '',
        userName: '',
        email: '',
        password: '',
        confirmPassword: ''
      };

      // 用户名验证
      if (!this.userName) {
        this.errors.userName = '请输入用户名';
        isValid = false;
      } else if (this.userName.length < 2 || this.userName.length > 16) {
        this.errors.userName = '用户名长度必须在2-16位之间';
        isValid = false;
      }

      // 手机号验证
      if (!this.phoneNumber) {
        this.errors.phoneNumber = '请输入电话号码';
        isValid = false;
      } else if (!/^1[3-9]\d{9}$/.test(this.phoneNumber)) {
        this.errors.phoneNumber = '请输入有效的11位手机号码';
        isValid = false;
      }

      // 邮箱验证（必填项）
      if (!this.email) {
        this.errors.email = '请输入电子邮箱';
        isValid = false;
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email)) {
        this.errors.email = '请输入有效的邮箱地址（例如：xxx@example.com）';
        isValid = false;
      }

      // 密码验证
      if (!this.password) {
        this.errors.password = '请输入密码';
        isValid = false;
      } else if (this.password.length < 6 || this.password.length > 20) {
        this.errors.password = '密码长度必须在6-20位之间';
        isValid = false;
      } else if (!/(?=.*[A-Za-z])(?=.*\d)/.test(this.password)) {
        this.errors.password = '密码必须包含字母和数字';
        isValid = false;
      }

      // 确认密码验证
      if (!this.confirmPassword) {
        this.errors.confirmPassword = '请确认密码';
        isValid = false;
      } else if (this.password !== this.confirmPassword) {
        this.errors.confirmPassword = '两次输入的密码不一致';
        isValid = false;
      }

      return isValid;
    },

    submitRegistration() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }

      // 构造符合后端要求的注册数据
      const registerData = {
        username: this.userName,
        password: this.password,
        email: this.email,
        phoneNumber: this.phoneNumber,
        avatarUrl: this.avatarFileUrl || ''
      };


      uni.showLoading({ title: '注册中...' });

      uni.request({
        url: API_BASE_URL + '/api/auth/register', 
        method: 'POST',
        data: registerData,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          uni.hideLoading();
          
          // 处理HTTP错误状态码
          if (res.statusCode < 200 || res.statusCode >= 300) {
            let errorMsg = `注册失败 (${res.statusCode})`;
            
            // 解析后端返回的错误信息
            if (res.data && res.data.message) {
              errorMsg = res.data.message;
            } else if (res.statusCode === 400 && res.data.errors) {
              // 处理模型验证错误
              const firstError = Object.values(res.data.errors)[0][0];
              errorMsg = firstError || errorMsg;
            }
            
            console.error('注册失败:', errorMsg);
            return uni.showToast({
              title: errorMsg,
              icon: 'none'
            });
          }
          
          // 处理业务逻辑结果
          if (res.data && res.data.success) {
            // 保存token
            if (res.data.token) {
              uni.setStorageSync('token', res.data.token);
            }
            
            // 构建完整的用户信息，使用id而不是userId，移除角色相关信息
            const userInfo = {
              userName: this.userName,
              email: this.email,
              phoneNumber: this.phoneNumber,
              avatarUrl: this.avatarFileUrl || '',
              id: res.data.userId || '', 
            };
            
            // 保存用户信息到本地存储
            uni.setStorageSync('userInfo', userInfo);
            
            uni.showToast({
              title: '注册成功',
              icon: 'success'
            });
            
            // 延迟跳转到登录页，使用redirectTo清除注册页
            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/login/login'
              });
            }, 1500);
          } else {
            uni.showToast({
              title: res.data?.message || '注册失败，请重试',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.hideLoading();
          console.error('注册请求失败', err);
          uni.showToast({
            title: '网络错误，注册失败',
            icon: 'none'
          });
        }
      });
    }
  }
}
</script>

<style scoped>
/* 基础样式重置 */
.register-container, .register-card, 
.title, .form-group, .input-field, .toggle-password, 
.bottom-buttons, .register-btn, .login-btn, form, 
.avatar-upload, .avatar-preview, .upload-icon, .avatar-hint, .input-hint {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/* 输入提示样式 */
.input-hint {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  text-align: left;
}

.register-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f9f9f9;
}

.register-card {
  width: 100%;
  background-color: white;
  padding: 30px 20px;
  min-height: 100vh;
}

.title {
  font-size: 24px;
  color: #333;
  text-align: center;
  margin-bottom: 30px;
  font-weight: 600;
}

/* 头像上传样式 */
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40px;
}

.avatar-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  border: 2px dashed #b3d9ff;
  background-color: rgba(179, 217, 255, 0.1);
  background-size: cover;
  background-position: center;
  position: relative;
  margin-bottom: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.avatar-preview:hover {
  border-color: #80d4ff;
  background-color: rgba(128, 212, 255, 0.1);
}

.upload-icon {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #80d4ff;
}

.icon {
  font-size: 30px;
  font-weight: bold;
}

/* 表单样式 */
.form-group {
  margin-bottom: 25px;
}

.input-field {
  width: 100%;
  padding: 16px 14px;
  border: 1px solid #ddd;
  border-radius: 12px;
  font-size: 17px;
  transition: border-color 0.3s;
  min-height: 56px;
}

.input-field:focus {
  outline: none;
  border-color: #80d4ff;
}

.error-message {
  color: #ff4d4f;
  font-size: 13px;
  margin-top: 5px;
  text-align: left;
  min-height: 18px;
}

/* 底部按钮样式 */
.bottom-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 30px;
}

.register-btn {
  width: 100%;
  padding: 16px 10px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 17px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.register-btn:hover {
  background-color: #096dd9;
}

.login-btn {
  width: 100%;
  padding: 16px 10px;
  background-color: white;
  color: #b3d9ff;
  border: 1px solid #b3d9ff;
  border-radius: 12px;
  font-size: 17px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.login-btn:hover {
  background-color: #f0f7ff;
}

/* 适配小屏幕设备 */
@media (max-width: 375px) {
  .input-field {
    padding: 16px 14px;
    min-height: 52px;
    font-size: 16px;
  }
  
  .toggle-password {
    height: 52px;
  }
  
  .register-btn, .login-btn {
    padding: 14px 10px;
    font-size: 16px;
  }
  
  .avatar-preview {
    width: 100px;
    height: 100px;
  }
}
</style>